#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QTcpServer>
#include <QTcpSocket>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QTableWidget>
#include <QStringList>
#include <QDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 创建一个TCP服务器
    server = new QTcpServer(this);
    connect(server, &QTcpServer::newConnection, this, &Widget::newConnection);

    // 在特定端口上开始监听
    if (!server->listen(QHostAddress::Any, 1234)) {
        QMessageBox::critical(this, tr("Server Error"), tr("无法启动服务器：%1").arg(server->errorString()));
        return;
    }

    // 打开SQLite数据库
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("/home/gjd/Qt/dictionary.db");
    if (!db.open()) {
        QMessageBox::critical(this, tr("Database Error"), tr("无法打开数据库"));
        return;
    }

    // 如果表不存在，则创建一个新表
    QSqlQuery query;
    query.exec("CREATE TABLE IF NOT EXISTS Users (Username TEXT PRIMARY KEY, Password TEXT)");

    // 创建 tableWidget 并设置列数
    tableWidget = new QTableWidget(this);
    tableWidget->setColumnCount(3);

    // 设置列标签
    QStringList headers;
    headers << "用户名" << "IP" << "端口";
    tableWidget->setHorizontalHeaderLabels(headers);

    // 设置 tableWidget 的位置和大小
    tableWidget->setGeometry(50, 90, 301, 191);

    qDebug() << "服务器已启动，等待客户端连接...";
}

Widget::~Widget()
{
    delete ui;
}

void Widget::newConnection()
{
    // 当有新连接建立时
    QTcpSocket *clientSocket = server->nextPendingConnection();
    connect(clientSocket, &QTcpSocket::readyRead, this, [this, clientSocket]() {
        onReadyRead(clientSocket);
    });

    qDebug() << "有客户端连接";
}

void Widget::onReadyRead(QTcpSocket *clientSocket)
{
    // 从客户端读取传入的数据
    QByteArray data = clientSocket->readAll();
    QString message = QString::fromUtf8(data);

    QStringList parts = message.split("\n", QString::SkipEmptyParts);

    QString requestType = parts[0];

    qDebug() << "获取信息";

    if (requestType == "REGISTER") {
        QString username = parts[1];
        QString password = parts[2];
        // 检查用户名是否已存在
        QSqlQuery query;
        query.prepare("SELECT Username FROM Users WHERE Username = ?");
        query.bindValue(0, username);
        if (query.exec() && query.next()) {
            // 用户名已存在
            sendResponse(clientSocket, "REGISTER_FAIL");
        } else {
            // 用户名不存在，进行注册
            query.prepare("INSERT INTO Users (Username, Password) VALUES (?, ?)");
            query.bindValue(0, username);
            query.bindValue(1, password);
            if (query.exec()) {
                // 创建新表
                QSqlQuery createTableQuery;
                QString createTableCmd = "CREATE TABLE " + username + " (Word TEXT)";
                if (createTableQuery.exec(createTableCmd)) {
                    qDebug() << "为用户建表";
                } else {
                    qDebug() << "建表失败";
                }
                sendResponse(clientSocket, "REGISTER_SUCCESS");
            } else {
                sendResponse(clientSocket, "REGISTER_FAIL");
            }
        }

    } else if (requestType == "LOGIN") {
        QString username = parts[1];
        QString password = parts[2];
        // 检查用户名和密码是否匹配
        QSqlQuery query;
        query.prepare("SELECT Username FROM Users WHERE Username = ? AND Password = ?");
        query.bindValue(0, username);
        query.bindValue(1, password);
        if (query.exec() && query.next()) {
            // 用户名和密码匹配
            sendResponse(clientSocket, "LOGIN_SUCCESS");
        } else {
            // 用户名和密码不匹配
            sendResponse(clientSocket, "LOGIN_FAIL");
        }
    } else if (requestType == "INQUIRE") {
        QString username = parts[1];
        QString word = parts[2];

        QSqlQuery query;
        query.prepare("SELECT Definition FROM Dictionary WHERE Word = ?");
        query.bindValue(0, word);

        if (query.exec() && query.next()) {
            // 找到了对应的定义
            QString definition = query.value(0).toString();
            QString message = "INQUIRE_SUCCESS\n";
            message += definition + "\n";
            sendResponse(clientSocket, message.toUtf8());

            qDebug() << "发送信息";

            QSqlQuery insertQuery;
            insertQuery.prepare("INSERT INTO " + username + " (Word) VALUES (?)");
            insertQuery.bindValue(0, word);

            if (insertQuery.exec()) {
                // 插入成功
                qDebug() << "成功向表中插入单词";
            } else {
                // 插入失败
                qDebug() << "插入单词失败";
            }
        } else {
            // 未找到对应的定义
            sendResponse(clientSocket, "INQUIRE_FAIL\nNONE\n");
        }
    } else if (requestType == "HISTORY") {
        QString username = parts[1];

        // 检查数据库中是否存在该用户的表
        QSqlQuery query;
        query.prepare("SELECT Word FROM " + username);

        if (query.exec()) {
            QStringList wordsList;
            while (query.next()) {
                QString word = query.value(0).toString();
                wordsList.append(word);
            }

            QString wordsData = wordsList.join("\n");
            QString message = "HISTORY_SUCCESS\n";
            message += wordsData + "\n";
            sendResponse(clientSocket, message);
        } else {
            sendResponse(clientSocket, "HISTORY_FAIL\nNONE\n");
        }
    } else if (requestType == "LOGIN_IN") {
        QString username = parts[1];

        // 获取客户端的用户名、IP 和端口信息
        QString ip = clientSocket->peerAddress().toString();
        QString port = QString::number(clientSocket->peerPort());

        // 将信息添加到 tableWidget
        int row = tableWidget->rowCount();
        tableWidget->insertRow(row);
        tableWidget->setItem(row, 0, new QTableWidgetItem(username));
        tableWidget->setItem(row, 1, new QTableWidgetItem(ip));
        tableWidget->setItem(row, 2, new QTableWidgetItem(port));
    } else if (requestType == "CLOSE") {
        QString username = parts[1];

        // 遍历表格的每一行
        for (int row = 0; row < tableWidget->rowCount(); ++row) {
            QTableWidgetItem *item = tableWidget->item(row, 0); // 获取第一列的单元格
            if (item && item->text() == username) { // 如果找到了要删除的用户名
                tableWidget->removeRow(row); // 删除整行
                break; // 找到并删除后，退出循环
            }
        }
    }
}

void Widget::sendResponse(QTcpSocket *clientSocket, const QString &responseType)
{
    // 向客户端发送响应
    QByteArray responseData;
    QDataStream responseStream(&responseData, QIODevice::WriteOnly);
    responseStream << responseType;
    clientSocket->write(responseData);

    qDebug() << "发送响应";
}
